<?php

namespace app\api\model;

use think\Model;
use traits\model\SoftDelete;

class Learnings extends Model
{
    use SoftDelete;
    protected $autoWriteTimestamp = 'int';
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';
    protected $hidden = ['deletetime', 'createtime', 'updatetime'];

    public function knowledgeImages()
    {
        return $this->hasMany(LearningImages::class, 'learning_id', 'id')->where('type', 'knowledge');
    }
    public function homeworkImages()
    {
        return $this->hasMany(LearningImages::class, 'learning_id', 'id')->where('type', 'homework');
    }

    public static function getByStudent($student_id, $date)
    {
        $startTime = strtotime($date);
        $endTime = $startTime + 86399;
        return self::with(['knowledgeImages', 'homeworkImages'])->where('student_id', $student_id)->whereTime('createtime', [$startTime, $endTime])->find();
    }

    public static function createLearning($student_id, $data)
    {
        return self::create([
            'student_id' => $student_id,
            'reading' => $data['reading'],
            'knowledge' => $data['knowledge'] ?? '',
            'homework' => $data['homework'] ?? ''
        ]);
    }

    public static function updateLearning($learning_id, $data)
    {
        return self::where('id', $learning_id)->update([
            'reading' => $data['reading'],
            'knowledge' => $data['knowledge'] ?? '',
            'homework' => $data['homework'] ?? ''
        ]);
    }

}
